/**
 * Created by shuyizhi on 2017/3/16.
 */
var ctx = "/deploy"

init();

Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.pushNoRepeat = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return;
    }
    this.push(val);
};

Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

//数组去重
Array.prototype.unique = function(){
    this.sort();
    var re=[this[0]];
    for(var i = 1; i < this.length; i++){
        if( this[i] !== re[re.length-1]){
            re.push(this[i]);
        }
    }
    return re;
}

String.prototype.startWith=function(str){     
	  var reg=new RegExp("^"+str);     
	  return reg.test(this);        
}  

String.prototype.endWith=function(str){     
	  var reg=new RegExp(str+"$");     
	  return reg.test(this);        
}


function init() {
    $(document).bind("keydown", function (e) {
        e = window.event || e;
        if (e.keyCode == 116) {
            e.keyCode = 0;
            parent.libs.refreshNowBreads();
            return false; //屏蔽F5刷新键
        }
    });
}

function ViewModel() {
    var self = this;
    self.items = ko.observableArray([]);
}

/*时间格式化*/
/*时间转换*/
function timeConvert(datetime) {
    //"2016-02-19T13:12:14.985+08:00"
    if (datetime == null || datetime == undefined)
        return '';
    var date = new Date(datetime);
    //var date = eval(datetime.replace(/\/Date\(([-|+]{0,1}\d+\+\d+)\)\//gi, "new Date($1)"));
    if (date != null && date != undefined) {
        var resdate = date.format("yyyy-MM-dd hh:mm:ss");
    }
    if (resdate.toUpperCase() == "NAN-AN-AN AN:AN:AN") {
        var isoExp = /(\d{4}-\d{1,2}-\d{1,2})(T|\s*)(\d{1,2}:\d{1,2}:[\d]{1,2})/;
        var parts = isoExp.exec(datetime);
        resdate = parts[1] + ' ' + parts[3];
    }
    if (resdate.indexOf("1970-01-01") > -1) {
        resdate = '';
    }
    return resdate;
}
/*时间格式化*/
/*时间转换*/
function timeConvertFormat(datetime,format) {
	//"2016-02-19T13:12:14.985+08:00"
	if (datetime == null || datetime == undefined)
		return '';
	var date = new Date(datetime);
	//var date = eval(datetime.replace(/\/Date\(([-|+]{0,1}\d+\+\d+)\)\//gi, "new Date($1)"));
	if (date != null && date != undefined) {
		var resdate = date.format(format);
	}
	if (resdate.toUpperCase() == "NAN-AN-AN AN:AN:AN") {
		var isoExp = /(\d{4}-\d{1,2}-\d{1,2})(T|\s*)(\d{1,2}:\d{1,2}:[\d]{1,2})/;
		var parts = isoExp.exec(datetime);
		resdate = parts[1] + ' ' + parts[3];
	}
	if (resdate.indexOf("1970-01-01") > -1) {
		resdate = '';
	}
	return resdate;
}
/*时间格式化*/
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}


function selectToRadio(obj, inputname) {

    $('input[name="' + inputname + '"]').each(function () {
        if (obj.checked && obj != this) {
            this.checked = false;
        }
    });


}
//不能取消
function selectToRadio2(obj, inputname) {

    $('input[name="' + inputname + '"]').each(function () {
        if (obj.checked && obj != this) {
            this.checked = false;
        } else if (obj.checked == false && obj == this) {
            this.checked = true;
        }
    });


}

//转义
function escapeHtml(string) {
    var entityMap = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };
    return String(string).replace(/[&<>"'\/]/g, function (s) {
        return entityMap[s];
    });
}
//反转义html
function unescapeHtml(str){
	if(str==undefined||str==null)return str;
	str = str.replace(/＜/g, "<");
    str = str.replace(/＞/g, ">");
    return str;
}

//转义
function escapelPre(str) {
	if(str==undefined||str==null)return str;
    str = str.replace(/\r/g, "&nbsp;");
    str = str.replace(/\n/g, "<br/>");
    return str;
}

//原样输出html
function showPre(divId) {
    var str = $("#" + divId).text();
    $("#" + divId).html(escapelPre(str));
}
//截取输出
function subTag(text, len) {
    if (text == null)return "";
    if (text.length <= len)return text;
    if (text.length > len) {
        text = text.substr(0, len) + "...";
    }
    return text;
}

//秒转天时分秒
function convertToDay(second) {
    var day_suffix = "天";
    var hour_suffix = "小时";
    var days = Math.floor(second / (24 * 3600))
    var leave1 = second % (24 * 3600)
    var hours = Math.floor(leave1 / (3600))
    return days + day_suffix + hours + hour_suffix;
}
//验证IP
function validateIp(ip) {
    var reg = /(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/ig;
    return reg.test(ip);
}
//端口验证(0~65535)
function validatePort(port) {
    var reg = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/ig;
    return reg.test(port);
}
//纬度（-90~90：）
function validatelatitude(coordinate) {
    var reg = /^[-]?(\d|([1-8]\d)|(90))(\.\d*)?$/g;
    return reg.test(coordinate);
}
//经度（-180~180）
function validatelongitude(coordinate) {
    var reg = /^[-]?(\d|([1-9]\d)|(1[0-7]\d)|(180))(\.\d*)?$/g;
    return reg.test(coordinate);
}

//中文标点、全半角转化
function exchange(txt) {
    var s = txt;
    /*正则转换中文标点*/
    s = s.replace(/：/g, ':');
    s = s.replace(/。/g, '.');
    s = s.replace(/“/g, '"');
    s = s.replace(/”/g, '"');
    s = s.replace(/【/g, '[');
    s = s.replace(/】/g, ']');
    s = s.replace(/《/g, '<');
    s = s.replace(/》/g, '>');
    s = s.replace(/，/g, ',');
    s = s.replace(/？/g, '?');
    s = s.replace(/、/g, ',');
    s = s.replace(/；/g, ';');
    s = s.replace(/（/g, '(');
    s = s.replace(/）/g, ')');
    s = s.replace(/‘/g, "'");
    s = s.replace(/’/g, "'");
    s = s.replace(/『/g, "[");
    s = s.replace(/』/g, "]");
    s = s.replace(/「/g, "[");
    s = s.replace(/」/g, "]");
    s = s.replace(/﹃/g, "[");
    s = s.replace(/﹄/g, "]");
    s = s.replace(/〔/g, "{");
    s = s.replace(/〕/g, "}");
    s = s.replace(/—/g, "-");
    s = s.replace(/·/g, ".");
    /*正则转换全角为半角*/
    //字符串先转化成数组
    s = s.split("");
    for (var i = 0; i < s.length; i++) {
        //全角空格处理
        if (s[i].charCodeAt(0) === 12288) {
            s[i] = String.fromCharCode(32);
        }
        /*其他全角*/
        if (s[i].charCodeAt(0) > 0xFF00 && s[i].charCodeAt(0) < 0xFFEF) {
            s[i] = String.fromCharCode(s[i].charCodeAt(0) - 65248);
        }
    }
    //数组转换成字符串
    s = s.join("");
    return s;
}







//数字格式化，如54321转换为54,321
function formatMoney(number, places, thousand, decimal) {
    number = number || 0;
    places = !isNaN(places = Math.abs(places)) ? places : 2;
    //symbol = symbol !== undefined ? symbol : "$";
    thousand = thousand || ",";
    decimal = decimal || ".";
    var negative = number < 0 ? "-" : "",
        i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    //return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");

    return negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousand);
}

//获取checkbox选中的值
function getChkBoxIds(n, s) {
    var chk = "";
    $('input[name="' + n + '"]:checked').each(function () {
        chk += $(this).val() + ",";
    });
    if (chk.length <= 0) {
        chk = "";
    }
    if (chk.length > 0) {
        chk = chk.substr(0, chk.length - 1);
    }
    if (s === 1) {
        if (chk.split(",").length > 1) {
            chk = "";
        }
    }
    return chk;
}


//获取checkbox选中的属性值
function getChkBoxAttrValues(elementName, attrName) {
    var chk = "";
    $('input[name="' + elementName + '"]:checked').each(function () {
        chk += $(this).attr(attrName) + ",";
    });
    if (chk.length <= 0) {
        chk = "";
    }
    if (chk.length > 0) {
        chk = chk.substr(0, chk.length - 1);
    }
    return chk;
}

/**
 * 编辑星星显示
 */
function  showStar(star){
	if (star == null || star == "") {
		return "stars"
	}else{
		return "stars star"+(star-1)
	}
}

//直接展示星星个数
function getStar(num) {
    var starHtml = "";
    for (var i = 0; i < 5; i++) {
        if (num > 0 && num > i) {
            starHtml += "<i class=\"iconfont icon-xing bright\"></i>";
        } else {
            starHtml += "<i class=\"iconfont icon-xing\"></i>";
        }
    }
    return starHtml;
}


function showImg(img,defaultIMg){
	if(img==null||img==""){
		return ctx+defaultIMg;
	}
	return ctx+img;
}

//layer弹出窗口关闭自己
function closeSelf() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index); //再执行关闭
}

///将long类型时间转换为YYYY-MM-DD格式
function stringToDate(longDate) {
    return timeConvert(longDate,'yyyy-MM-dd');
}

///将long类型时间转换为YYYY-MM-DD hh:mm:ss格式
function stringToTime(longDate) {
    return timeConvert(longDate,'yyyy-MM-dd hh:mm:ss');
}

$(function () {
    if(jQuery.validator != null && jQuery.validator != ""){
        //jQuery 表单验证拓展方法
        jQuery.validator.addMethod("isIntGtZero", function (value, element) {
			var s = $.trim(value);
			if (!/^[1-9]+[0-9]*]*$/.test(s)) {
	        return false;
	    }
	    return true;
            
        }, "整数且必须大于0");
        //jQuery 表单验证拓展方法
        jQuery.validator.addMethod("isIntNumber", function (value, element) {
        	var s = $.trim(value);
        	if (!/(0|^[1-9]\d*$)/.test(s)) {
        		return false;
        	}
        	return true;
        }, "整数包含0");

        // 只能包含中文、英文、数字、下划线
        jQuery.validator.addMethod("notSpecialChar", function (value, element) {
         //   return this.optional(element) || /^[A-Za-z0-9_]+$/.test(value);
			if (/([~!@#$%&*()`=+,;?<>-]|\\|\'|\")/.test(value)) {
		        return false;
		    }
			return true;
        }, "不能包含特殊字符");
        jQuery.validator.addMethod("noSpace", function (value, element) {
			if (value.trim().length==0) {
		        return false;
		    }
			return true;
        }, "不能只输入空格");

        // 手机号码验证
        jQuery.validator.addMethod("isMobile", function (value, element) {
            var length = value.length;
            return this.optional(element) || (length == 11 && /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value));
        }, "输入的手机号码不正确");
        //验证小数点后面1位
        jQuery.validator.addMethod("minNumber",function(value, element){
            var returnVal = true;
            inputZ=value;
            var ArrMen= inputZ.split(".");    //截取字符串
            if(ArrMen.length==2){
                if(ArrMen[1].length>1){    //判断小数点后面的字符串长度
                    returnVal = false;
                    return false;
                }
            }
            return returnVal;
        },"小数点后最多为1位");         //验证错误信息
        
        //ip
        jQuery.validator.addMethod("ip", function(value, element) { 
        	var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/; 
        	return this.optional(element) || (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256)); 
        	}, "Ip地址格式错误");
        //中文
        jQuery.validator.addMethod("chinese", function(value, element) {
        	var chinese = /^[\u4e00-\u9fa5]+$/;
        	return this.optional(element) || (chinese.test(value));
        	}, "只能输入中文");
        
        //端口校验
        jQuery.validator.addMethod("portCheck", function(value, element) {
        	   var reg = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/ig;
        	return this.optional(element) || (reg.test(value));
        }, "只能输入0~65535");
        //匹配域名
        jQuery.validator.addMethod("domain", function(value, element) {
        	var chinese = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
        	return this.optional(element) || (chinese.test(value));
        	}, "域名格式不匹配");
    }
})

//重置副文本框
function restForm(){
	$(".wangEditor-txt").html('<p><br></p>');
}

//全部替换字符串中的内容
function strReplaceAll(strAll,oldStr,newStr){
	var regexp=new RegExp(oldStr,"g");
	if(strAll!=null&&typeof(strAll)!="undefined"){
		return strAll.replace(regexp,newStr);
	}else{
		return "";
	}
}

function isEmpty(str){
	if(str==null||str==undefined||str.trim()==''){
		return true
	}
	return false;
}

function myTimeConvert(time) {
    if(time != null && time != ""){
        return timeConvert(parseInt(time)*1000);
    }
    return "暂未上传";
}

/**
 * 异步文件上传
 * @param url 路径
 * @param fileInputId 文件上传inputid
 * @param callBack 回调
 */
function asyncFileUpload(url,fileInputId,callBack,errorBack) {
    var formData = new FormData();
    formData.append("customFileName",document.getElementById(fileInputId).files[0]);
    $.ajax({
        type: "POST",
        url: url,
        data: formData,
        dataType: "json",
        processData: false,
        contentType: false,
        success: function(data){
            if(data.state){
                callBack(data.model.fileName,data.model.filePath);
            }else{
                layer.msg(data.message,{icon:2});
                errorBack(data);
            }
        }
    });
}

$.fn.serializeJson=function(){
    var serializeObj={};
    var array=this.serializeArray();
    var str=this.serialize();
    $(array).each(function(){
        if(serializeObj[this.name]){
            if($.isArray(serializeObj[this.name])){
                serializeObj[this.name].push(this.value);
            }else{
                serializeObj[this.name]=[serializeObj[this.name],this.value];
            }
        }else{
            serializeObj[this.name]=this.value;
        }
    });
    return serializeObj;
};

//判断是否为正确的ip或者ip段
function isRightIp(ipAddress) {
    var ips = ipAddress.split(".");
    if (ips.length == 4) {
        for (var i = 0; i < ips.length; i++) {
            if (i == 3 && ips[i].indexOf("/") > -1) {
                var ipPlace = ips[i].split("/");
                if (ipPlace.length == 2) {
                    if (Number(ipPlace[0]) < 0 || Number(ipPlace[0]) > 255||isNaN(Number(ipPlace[0]))) {
                        return false;
                    }
                    if (Number(ipPlace[1]) < 0 || Number(ipPlace[1]) > 32||isNaN(Number(ipPlace[1]))) {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {
                if (Number(ips[i]) < 0 || Number(ips[i]) > 255||isNaN(Number(ips[i]))) {
                    return false;
                }
            }
        }
        return true;
    } else {
        return false;
    }
}